package com.testing.base;

import com.testing.Utlis.IniUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

/**
 * 用于获取元素对象和时间等待，这里不会有对元素操作的方法
 */
public class BasePageElement extends BaseDriver {

    // 显示等待
    protected WebDriverWait wait;

    // 浏览器驱动
    protected WebDriver driver;

    public BasePageElement(WebDriver driver) {
        this.driver = driver;
        this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }


    /**
     * 判断元素定位类型，获取定位
     *
     * @param iniKey ini文件中数据的key
     * @return 返回元素定位值
     */
    public By findLocateType(String iniKey) {
        By locator = null;
        String str = IniUtils.readIniFile(IniUtils.INIFILEPATH).get(iniKey);
        int index = str.indexOf(">");
        String locatorType = str.substring(0, index).trim();
        String locatorValue = str.substring(index + 1).trim();
        switch (locatorType) {
            case "xpath":
                locator = By.xpath(locatorValue);
                break;
            case "id":
                locator = By.id(locatorValue);
                break;
            case "name":
                locator = By.name(locatorValue);
            case "className":
                locator = By.className(locatorValue);
                break;
            case "cssSelector":
                locator = By.cssSelector(locatorValue);
                break;
            case "linkText":
                locator = By.linkText(locatorValue);
                break;
            case "partialLinkText":
                locator = By.partialLinkText(locatorValue);
                break;
            case "tagName":
                locator = By.tagName(locatorValue);
                break;
            default:
                System.out.println("没有这个定位方式");
        }
        return locator;
    }

    //获取元素方法
    public WebElement findElement(String iniKey) {
        By locate = new BasePageElement(driver).findLocateType(iniKey);
        return wait.until(presenceOfElementLocated(locate));
    }

    // 获取元素列表
    public List<WebElement> findElements(String iniKey) {
        // 假设 findLocateType 方法返回正确的 By 定位器
        By locate = new BasePageElement(driver).findLocateType(iniKey);

        // 等待至少有一个元素可用（虽然这里实际上只是等待第一个元素出现）
        wait.until(ExpectedConditions.presenceOfElementLocated(locate));

        // 获取所有匹配的元素
        return driver.findElements(locate);
    }


    // 等待时间
    public static void latencyTime(Integer time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
